<template>
  <view class="container">
    <map 
      id="qqMap" 
      class="map-container"
      :longitude="longitude" 
      :latitude="latitude" 
      :scale="scale"
      :markers="markers"
      :polyline="polyline" 
      @tap="onMapTap"
      @regionchange="onRegionChange"
      show-location
    ></map>
    <view class="info-box" v-if="showInfo">
      <text class="info-text">小黄牛位于您 <text class="direction-text">{{direction}}</text> {{distance.toFixed(0)}}米</text>
      <text class="info-tip">请沿着指示方向前行</text>
    </view>
    <view class="loading" v-if="loading">
      <text>正在加载地图...</text>
    </view>
    <view class="permission-tip" v-if="!hasLocationPermission">
      <text class="tip-text">请授予位置权限以使用地图功能</text>
      <button class="auth-btn" @click="requestLocationPermission">授权位置</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      latitude: 22.254515,
      longitude: 113.469689,
      scale: 14,
      markers: [],
      userLatitude: null,
      userLongitude: null,
      cowLatitude: 29.255,
      cowLongitude: 106.468,
      showInfo: false,
      direction: '',
      distance: 0,
      polyline: [{
        points: [],
        color: '#0066FF',
        width: 6,
        arrowLine: true
      }],
      loading: true,
      hasLocationPermission: false
    }
  },
  onLoad() {
    this.initMap();
  },
  methods: {
    // 初始化地图
    initMap() {
      this.loading = true;
      this.checkLocationPermission();
    },
    
    // 检查位置权限
    checkLocationPermission() {
      uni.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userLocation']) {
            this.hasLocationPermission = true;
            this.getUserLocation();
          } else {
            this.hasLocationPermission = false;
            this.requestLocationPermission();
          }
        },
        fail: (err) => {
          console.error('获取权限设置失败:', err);
          this.loading = false;
        }
      });
    },
    
    // 请求位置权限
    requestLocationPermission() {
      uni.authorize({
        scope: 'scope.userLocation',
        success: () => {
          this.hasLocationPermission = true;
          this.getUserLocation();
        },
        fail: (err) => {
          console.error('请求位置权限失败:', err);
          this.hasLocationPermission = false;
          this.loading = false;
          
          // 显示权限提示
          uni.showModal({
            title: '权限申请',
            content: '需要位置权限才能显示牛群位置',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting();
              }
            }
          });
        }
      });
    },
    
    // 获取用户位置
    getUserLocation() {
      uni.getLocation({
        type: 'wgs84', // 这里使用wgs84坐标系，可根据实际情况调整，部分平台返回的可能是gcj02，需做转换
        success: (res) => {
          console.log('获取位置成功:', res);
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          this.userLatitude = res.latitude;
          this.userLongitude = res.longitude;
          
          // 更新标记点
          this.markers = this.markers.map(marker => {
            if (marker.id === 1) {
              marker.latitude = this.latitude;
              marker.longitude = this.longitude;
            }
            return marker;
          });
          
          this.calculateDirectionAndDistance();
          this.showInfo = true;
          this.getRoute();
          this.loading = false;
        },
        fail: (err) => {
          console.error('获取位置失败:', err);
          uni.showToast({
            title: '请授权位置访问',
            icon: 'none'
          });
          this.loading = false;
        }
      });
    },
    
    // 计算方向和距离
    calculateDirectionAndDistance() {
      if (!this.userLatitude || !this.userLongitude) return;
      
      // 计算距离（简化版，实际项目建议使用专业库）
      const R = 6371e3; // 地球半径（米）
      const φ1 = this.userLatitude * Math.PI / 180;
      const φ2 = this.cowLatitude * Math.PI / 180;
      const Δφ = (this.cowLatitude - this.userLatitude) * Math.PI / 180;
      const Δλ = (this.cowLongitude - this.userLongitude) * Math.PI / 180;
      
      const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
                Math.cos(φ1) * Math.cos(φ2) *
                Math.sin(Δλ/2) * Math.sin(Δλ/2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      
      this.distance = R * c; // 距离（米）
      
      // 计算方向
      const y = Math.sin(Δλ) * Math.cos(φ2);
      const x = Math.cos(φ1)*Math.sin(φ2) -
                Math.sin(φ1)*Math.cos(φ2)*Math.cos(Δλ);
      const bearing = Math.atan2(y, x) * 180 / Math.PI;
      
      // 转换为方向描述
      const directions = ['北', '东北', '东', '东南', '南', '西南', '西', '西北'];
      const index = Math.floor((bearing + 360) % 360 / 45);
      this.direction = directions[index];
    },
    
    // 获取路线规划
    getRoute() {
      if (!this.userLatitude || !this.userLongitude) {
        console.error('用户位置信息不存在');
        return;
      }
      
      const qqmapsdk = getApp().globalData.qqmapsdk;
      if (!qqmapsdk) {
        console.error('腾讯地图SDK未初始化');
        uni.showToast({
          title: '地图服务不可用',
          icon: 'none'
        });
        return;
      }
      
      console.log('请求路线规划:', this.userLatitude, this.userLongitude, this.cowLatitude, this.cowLongitude);
      
      qqmapsdk.direction({
        mode: 'walking',
        from: `${this.userLatitude},${this.userLongitude}`,
        to: `${this.cowLatitude},${this.cowLongitude}`,
        success: (res) => {
          console.log('路线规划成功:', res);
          if (res.result && res.result.routes && res.result.routes.length > 0) {
            const points = res.result.routes[0].polyline;
            if (points.length === 0) {
              console.error('获取到的路线坐标为空');
              uni.showToast({
                title: '路线数据异常',
                icon: 'none'
              });
              return;
            }
            const coors = [];
            let prevLat = 0;
            let prevLng = 0;
            
            // 坐标解压（返回的点串坐标，通过前向差分进行压缩）
            for (let i = 0; i < points.length; i += 2) {
              if (i + 1 >= points.length) {
                console.error('坐标数据格式错误');
                uni.showToast({
                  title: '路线数据错误',
                  icon: 'none'
                });
                return;
              }
              const lat = points[i] / 1000000 + prevLat;
              const lng = points[i + 1] / 1000000 + prevLng;
              coors.push({
                latitude: lat,
                longitude: lng
              });
              prevLat = lat;
              prevLng = lng;
            }
            
            this.polyline[0].points = coors;
          } else {
            console.error('未获取到有效路线数据:', res);
            uni.showToast({
              title: '路线规划失败',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('获取路线失败:', error);
          uni.showToast({
            title: '获取路线失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 地图点击事件
    onMapTap(e) {
      console.log('地图点击:', e);
    },
    
    // 地图区域变化事件
    onRegionChange(e) {
      console.log('地图区域变化:', e);
    }
  }
}
</script>

<style>
.container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
}

.info-box {
  position: fixed;
  bottom: 20px;
  left: 20px;
  right: 20px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
  text-align: center;
  z-index: 10;
}

.info-text {
  font-size: 16px;
  color: #333;
}

.direction-text {
  color: #0066FF;
  font-weight: bold;
}

.info-tip {
  font-size: 14px;
  color: #666;
}

.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 12px 16px;
  border-radius: 8px;
  z-index: 20;
}

.permission-tip {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  text-align: center;
  z-index: 30;
  width: 80%;
}

.tip-text {
  font-size: 16px;
  margin-bottom: 15px;
  display: block;
}

.auth-btn {
  background-color: #0066FF;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 16px;
  width: 100%;
}
</style>